import React, { Component } from 'react';
import { Table, Pagination, Message, Dialog, Button, Balloon, Grid, Upload, Loading } from '@alifd/next';
import IceContainer from '@icedesign/container';
import TableFilter from './TableFilter';
import EditForm from '../EditForm';
import SearchTableWrapper from '#/hoc/SearchTableWrapper'
import { ApiOfMetricPage, ApiOfMetricDelete, ApiOfMetricDeleteBatch } from '#/utils/coreApiDefine'
import { ApiOfMetricImport, ApiOfMetricTemplate } from '#/utils/coreApiDefine'

const { Row, Col } = Grid;

@SearchTableWrapper(ApiOfMetricPage)
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      detailDialogVisible: false,
      editInstance: {},
      rowSelection: {
        onChange: this.onRowSelectChange.bind(this),
        selectedRows: [],
        selectedRowKeys: [],
      },
      actionBarLoadingVisible: false,
    };
  }

  // 渲染解析规则JSON显示
  renderRuleDesc = (value, index, item) => {
    let that = this;
    if (!item.rule) {
      return (
        <div></div>
      );
    } else {
      let rule = JSON.parse(item.rule);
      return (
        <div>
          {Object.keys(rule).map(function (k) {
            return (
              <dl style={styles.horizontal.dl} key={k}>
                <dt style={styles.horizontal.dt}>{k}:</dt>
                <dd style={styles.horizontal.dd}>{rule[k]}</dd>
              </dl>
            );
          })}
        </div>
      );
    }
  }

  // 渲染操作按钮示例
  renderOper = (value, index, item) => {
    let that = this;
    return (
      <div>
        <Button onClick={() => this.onOpenDetailDialog(item)} type="primary" text>编辑</Button>
        <span style={that.props.styles.separator} />
        <Button onClick={() => this.props.deleteConfirm(item, this.onDeleteConfirmOk.bind(this))} type="primary" text>删除</Button>
      </div>
    );
  }

  //打开编辑对话框
  onOpenDetailDialog = (item) => {
    this.setState({
      detailDialogVisible: true,
      editInstance: item ? item : {}
    });
  }

  //关闭编辑对话框
  onCloseDetailDialog = reason => {
    this.setState({
      detailDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }

  // 打开删除确认框
  onDeleteConfirmOk = item => {
    return ApiOfMetricDelete(item.code)
  }

  // 选择模式时，选择项改变事件
  onRowSelectChange(ids, records) {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = ids;
    rowSelection.selectedRows = [...rowSelection.selectedRows, ...records]
    this.setState({ rowSelection });
  }

  // 选择模式时，选择好后的确认事件
  onSelectConfirm() {
    let possibleRows = this.state.rowSelection.selectedRows,
      selectedRowKeys = this.state.rowSelection.selectedRowKeys;
    let selectedRows = possibleRows.filter(row => selectedRowKeys.findIndex(key => key == row.id) != -1)
    this.props.onSelect(selectedRows)
  }

  onBatchDeleteConfirm = () => {
    let that = this;
    Dialog.confirm({
      title: '',
      content: '确认要全部删除吗?',
      onOk: () => {
        that.setState({
          actionBarLoadingVisible: true
        })

        ApiOfMetricDeleteBatch(that.state.rowSelection.selectedRowKeys).then(response => {
          that.setState({
            actionBarLoadingVisible: false
          })
          that.props.fetch();
          Message.success('操作成功!');
        })
      }
    });
  }

  beforeUpload = (info) => {
    //console.log('beforeUpload : ', info);
    if (info.size > 5242880) {
      Message.error('上传文件过大,超过5M；文件名：' + info.name);
      return false;
    }
    var ss = info.name.substr(info.name.lastIndexOf(".")).toLowerCase();
    if (ss != '.xlsx') {
      Message.error('文件格式不支持,请选择.xlsx的文件；文件名：' + info.name);
      return false;
    }
    Message.loading('上传文件中,请等待；文件名：' + info.name);
  }
  onSuccess = (info) => {
    var status = info.response.status;
    // console.log(info);
    if ('success' === status) {
      this.props.fetch();
      Message.show({
        type: 'success',
        title: '指标导入',
        duration: 5000,
        content: '导入成功：' + info.name
      });
    } else if ('failure' === status) {
      Message.show({
        type: 'error',
        title: '指标导入',
        duration: 10000,
        content: '导入失败，错误原因：' + info.response.errors[0].errmsg
      });
      this.props.fetch();
      return false;
    }
  }
  onError = (info) => {
    Message.error('导入失败，错误原因：' + info.response.errors[0].errmsg);
    return false;
  }

  render() {
    const { instances } = this.props.bindingData;

    let DisplayTable, ActionBar;
    if (this.props.forSelectUsage === true) {
      DisplayTable =
        <div>
          <Table
            dataSource={instances.data}
            primaryKey="id"
            loading={this.props.loading}
            hasBorder={false}
            style={{ padding: '0 20px 20px' }}
            onSort={this.props.handleSort}
            rowSelection={this.state.rowSelection}

          >
            <Table.Column width={200} title="名称" dataIndex="name" sortable={true} />
            <Table.Column width={150} title="编号" dataIndex="code" />
            <Table.Column width={180} title="标识符" dataIndex="variable" />
            <Table.Column width={120} title="数据类型" dataIndex="valueType" />
            <Table.Column width={280} title="指令" dataIndex="command" />
            <Table.Column
              width={200}
              title="解析规则"
              cell={this.renderRuleDesc}
            />
          </Table>
          <TableFilter
            filter={this.props.filter}
            forSelectUsage={this.props.forSelectUsage}
            match={this.props.match}
          />
        </div>

      ActionBar =
        <Button onClick={this.onSelectConfirm.bind(this)} type="primary" size="small">选好了</Button>;
    } else {
      DisplayTable =
        <div>
          <Table
            dataSource={instances.data}
            loading={this.props.loading}
            hasBorder={false}
            style={{ padding: '0 20px 20px' }}
            onSort={this.props.handleSort}
            rowSelection={this.state.rowSelection}
          >
            <Table.Column width={200} title="名称" dataIndex="name" sortable={true} />
            <Table.Column width={150} title="编号" dataIndex="code" />
            <Table.Column width={180} title="标识符" dataIndex="variable" />
            <Table.Column width={120} title="数据类型" dataIndex="valueType" />
            <Table.Column width={240} title="指令" dataIndex="command" />
            <Table.Column
              width={200}
              title="解析规则"
              cell={this.renderRuleDesc}
            />
            <Table.Column
              width={100}
              title="操作"
              cell={this.renderOper}
            />
          </Table>
        </div>

      ActionBar =
        <div style={styles.formItem}>
          <Loading visible={this.state.actionBarLoadingVisible}>
            <div>
              <Button onClick={this.onBatchDeleteConfirm.bind(this, true)} disabled={this.state.rowSelection.selectedRowKeys.length == 0} size="small" type="normal">
                全部删除
              </Button>
            </div>
          </Loading>
          <form method="get" action={ApiOfMetricTemplate}>
            <button className="next-btn next-small next-btn-secondary" style={{ 'marginLeft': '10px' }}>下载模版</button>
          </form>
          <div>
            <Upload
              action={ApiOfMetricImport}
              beforeUpload={this.beforeUpload}
              onSuccess={this.onSuccess}
              onError={this.onError}
              multiple
              accept='.xlsx'
            >
              <Button type="normal" size="small" style={styles.submitButton} style={{ 'marginLeft': '10px' }}>
                导入
              </Button>
            </Upload>
          </div>
          <Button onClick={() => this.onOpenDetailDialog()} type="primary" size="small" style={{ 'marginLeft': '10px' }}>创建</Button>
        </div>
    }

    return (
      <IceContainer style={this.props.styles.container}>
        <TableFilter
          filter={this.props.filter}
          forSelectUsage={this.props.forSelectUsage}
          match={this.props.match}
        />
        <Row wrap gutter="20" style={styles.formRow}>
          <Col l="8">
            {ActionBar}
          </Col>
          <Col l="16">
            <Pagination
              style={{ 'marginBottom': '10px', ...this.props.styles.pagination }}
              shape="arrow-only"
              pageSizeSelector="filter"
              current={this.props.page}
              total={instances.pageable.totalElements}
              totalRender={total => `总数: ${total}`}
              pageSize={instances.pageable.size}
              onChange={this.props.handlePaginationChange}
              onPageSizeChange={this.props.handlePageSizeChange}
            />
          </Col>
        </Row>

        {DisplayTable}
        <Pagination
          style={this.props.styles.pagination}
          shape="arrow-only"
          pageSizeSelector="filter"
          current={this.props.page}
          total={instances.pageable.totalElements}
          totalRender={total => `总数: ${total}`}
          pageSize={instances.pageable.size}
          onChange={this.props.handlePaginationChange}
          onPageSizeChange={this.props.handlePageSizeChange}
        />
        <Dialog
          style={{ width: '50%' }}
          title="修改指标信息"
          visible={this.state.detailDialogVisible}
          footer={false}
          onClose={this.onCloseDetailDialog}>
          <EditForm formData={this.state.editInstance} submitCallback={this.onCloseDetailDialog} />
        </Dialog>
      </IceContainer>
    );
  }
}

const styles = {
  formRow: {
    padding: '10px 20px',
  },
  formItemRight: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
    float: 'right',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
  },
  horizontal: {
    dl: {
      marginTop: '3px',
      marginBottom: '3px',
    },
    dt: {
      float: 'left',
      width: '10%',
      overflow: 'hidden',
      clear: 'left',
      textAlign: 'right',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
    },
    dd: {
      marginLeft: '12%',
    }
  }
}
